package com.wennimei.controllers.weibo;

import net.paoding.rose.web.Invocation;
import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import weibo4j.Account;
import weibo4j.Oauth;
import weibo4j.Users;
import weibo4j.model.User;
import weibo4j.org.json.JSONObject;

import com.wennimei.enums.MessageTypeEnum;
import com.wennimei.enums.ResponseType;
import com.wennimei.service.MessageTypeService;
import com.wennimei.service.ProcessService;

@Path("")
public class WeiboController {

    private static final Logger log = Logger.getLogger("WEIBO");

    @Autowired
    private ProcessService processService;

    @Autowired
    private MessageTypeService messageTypeService;

    @Get
    @Post
    public String index(Invocation inv, @Param("content") String content) {
        boolean flag = false;
        try {
            String code = inv.getParameter("signed_request");
            inv.addModel("signed_request", code);
            Oauth auth = new Oauth();
            code = auth.parseSignedRequest(code);

            Account am = new Account();
            am.client.setToken(code);
            JSONObject uid = am.getUid();
            Users users = new Users();
            users.client.setToken(code);
            User user = users.showUserById(uid.getString("uid"));
            inv.addModel("user", user);

            if (null != content) {
                MessageTypeEnum type = this.messageTypeService.getMessageType(
                        content, "test");

                String result = null;
                Object res = this.processService.getContentResult(type,
                        content, null, null, "test");
                if (type.getRespType().equals(ResponseType.CONTENT)) {
                    if (null == res)
                        res = "没有查到任何信息哦，回复h查看使用帮助！";
                    result = (String) res;
                }

                inv.addModel("result", result.replaceAll("\r\n", "<br/>"));
            }
        } catch (Exception e) {
            flag = true;
        }
        inv.addModel("flag", flag);
        return "index";
    }
}
